package com.jerry.usbserial.fragment.usb

import android.annotation.SuppressLint
import android.content.Context
import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AlertDialog
import com.jerry.usbserial.R
import com.jerry.usbserial.adapter.MenuAdapter
import com.jerry.usbserial.util.*
import com.jerry.usbserial.util.task.usb.UsbMenuTask
import kotlinx.android.synthetic.main.bar_common.*
import kotlinx.android.synthetic.main.frg_menu_edit.*
import kotlinx.android.synthetic.main.item_menu_header.*

class UsbMenuFragment : UsbFragment() {
    private lateinit var menuAdapter: MenuAdapter

    override val layoutId: Int = R.layout.frg_menu_edit

    @SuppressLint("SetTextI18n")
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        toolbar_title.text = "USB编辑菜单"
        toolbar.inflateMenu(R.menu.menu_update)
        toolbar.setOnMenuItemClickListener {
            if (it.itemId == R.id.update) {
                getMenuItemList()
                return@setOnMenuItemClickListener true
            }
            if (it.itemId == R.id.add) {
                menuAdapter.addMenu()
                return@setOnMenuItemClickListener true
            }
            return@setOnMenuItemClickListener false
        }

        select_all.setOnCheckedChangeListener { cb, b ->
            if (cb.isPressed) menuAdapter.chooseAll(b)
        }

        menuAdapter = MenuAdapter(activity as Context)
        val json = mContext.getSp().getString("menu_data", null)
        json?.let {
            menuAdapter.updateMenu(it.jsonToList())
        }
        menuAdapter.setOnSelectedChanged {
            select_all.isChecked = menuAdapter.isChosenAll()
        }
        select_all.isChecked = menuAdapter.isChosenAll()
        listView.adapter = menuAdapter

        bt_update.setOnClickListener {
            val waitSendList = menuAdapter.getDataByChecked() ?: return@setOnClickListener

            val usbService = getUsbService()
            if (usbService == null) {
                mContext.showToast("Usb服务不可用")
                return@setOnClickListener
            }
            bt_update.isEnabled = false
            startTask(UsbMenuTask(mContext, usbService, waitSendList))
        }

        if (isDeviceConnected()) {
            bt_update.isEnabled = true
            bt_update.text = "更新菜单"
        }
    }

    override fun onMessageEvent(event: MsgEvent) {
        super.onMessageEvent(event)
        when (event.code) {
            MsgEventCode.STATE -> {
                if (event.msg == "设备已连接") {
                    bt_update.isEnabled = true
                    bt_update.text = "更新菜单"
                } else {
                    bt_update.isEnabled = false
                    bt_update.text = "请连接设备"
                }
            }
            MsgEventCode.MESSAGE -> {

            }
            MsgEventCode.PROCESS -> {
                progressBar.visibility = View.VISIBLE
                progressBar.setProgress(event.process)
            }
            MsgEventCode.COMPLETED -> {
                closeTask()
                bt_update.isEnabled = true
                progressBar.visibility = View.INVISIBLE

                AlertDialog.Builder(mContext).apply {
                    setTitle("提示")
                    setMessage(event.msg)
                    setCancelable(false)
                    setPositiveButton("确定") { _, _ -> }
                }.show()
            }
            MsgEventCode.ERROR -> {
                closeTask()
                bt_update.isEnabled = true
                progressBar.visibility = View.INVISIBLE

                AlertDialog.Builder(mContext).apply {
                    setTitle("提示")
                    setMessage(event.msg)
                    setCancelable(false)
                    setPositiveButton("确定") { _, _ -> }
                }.show()
            }
        }
    }

    private fun getMenuItemList() {
        RemoteRepo.getApi().menuItemList().applySchedulers(this)
            .subscribe(object : ResultObserver<List<MenuItem>>() {
                override fun handlerSuccess(data: List<MenuItem>) {
                    if (data.isNotEmpty()) {
                        menuAdapter.updateMenu(data)
                    }
                }

                override fun handlerError(code: Int, msg: String) {
                    mContext.showToast("数据获取失败")
                }
            })
    }
}